const { resolve } = require('path')
const { parse, build } = require('node-xlsx');
const fs = require("fs");

/**
 * 从js文件读取国际化数据
 * @param {string} fileName 文件名 可加后缀也可以不加
 * @returns {{[key:string]:any}}
 * @example
 * // 待读取js文件需要放在 `asset/i18n`目录下
 *      readDataFromJS('中文词条')
 *      readDataFromJS('中文词条.js')
 */
function readDataFromJS(fileName) {
    fileName = `${fileName}`
    if (!fileName.endsWith('.js')) fileName = `${fileName}.js`;
    const path = resolve(__dirname, './asset/i18n', fileName)
    return require(path)
}

/**
 * 从xls读取数据
 * @param {string} fileName 文件名 可加后缀也可以不加
 * @returns {Array<{name:string,data:Array<any>}>}
 * @example
 * // 待读取js文件需要放在 `asset/i18n`目录下
 *      readDataFromJS('xls词条')
 *      readDataFromJS('xls词条.xls')
 *      readDataFromJS('xls词条.xlsx')
 */
function readDataFromXLS(fileName) {
    fileName = `${fileName}`
    if (!fileName.endsWith('.xls') && !fileName.endsWith('xlsx')) fileName = `${fileName}.xls`;
    const path = resolve(__dirname, './asset/xls', fileName)
    let data = parse(path);
    return data;
}

/**
 * 遍历json数据直至键值为非引用类型
 * @param {(key:string,keyValue:string|number|boolean|symbol)=>void} cb 遍历回调函数
 * @param {{[key:string]:any}} data json数据
 * @param {string} [prekey] 前缀
 * @example
 * foreachJson('文件名.js',(item,i)=>{
 *      item.push(`这是第${i+1}条数据`)
 * })
 */
function foreachJson(cb, data, prekey = '') {
    Object.keys(data).forEach(key => {
        if (typeof data[key] == 'object' && data[key] != null) {
            foreachJson(cb, data[key], prekey ? `${prekey}.${key}` : key)
        } else {
            if (!!prekey) {
                if (cb instanceof Function) {
                    cb(`${prekey}.${key}`, data[key])
                }
            } else {
                if (cb instanceof Function) {
                    cb(`${key}`, data[key])
                }
            }
        }
    })
}

/**
 * 遍历xls文件数据
 * @param {Array<Array<any>>} xlsData xls数据 
 * @param {(item:Array<any>,index:number)} cb 循环回调 
 * @example
 * foreachXlsData([['1','2','3']],(item,i)=>{
 *      item.push(`这是第${i+1}条数据`)
 * })
 */
function foreachXlsData(xlsData, cb) {
    xlsData.forEach((item, index) => {
        if (cb instanceof Function) {
            cb(item, index)
        }
    })
}

/**
 * 将js data 数据写入xls
 * @param {string} jsFileName 
 * @param {string} xlsFileName 
 * @param {(store:Array<Array<any>>,key:string,data:any)=>void} format 
 */
function writeJSFileData2Xls(jsFileName, xlsFileName, format) {
    xlsFileName = `${xlsFileName}`
    const jsonData = readDataFromJS(jsFileName);
    let xlsData = []

    foreachJson((key, keyValue) => {
        format(xlsData, key, keyValue)
    }, jsonData)

    buildAndWriteXls(xlsData, xlsFileName)
}

/**
 * 构建xls文件信息
 * @param {*} xlsData 
 * @param {*} xlsFileName 
 * @param {*} sheetName 
 */
function buildAndWriteXls(xlsData, xlsFileName, sheetName) {
    const time = new Date();
    sheetName = sheetName ?? `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()}`
    const buffer = build([{ name: sheetName, data: xlsData }]);
    xlsFileName = (xlsFileName.endsWith('.xls') || xlsFileName.endsWith('xlsx')) ? xlsFileName : `${xlsFileName}.xls`
    const writePath = resolve(__dirname, 'src', '../asset/xls', xlsFileName)
    fs.writeFileSync(writePath, buffer)
}
/**
 * 构建js文件信息
 * @param {{[key:string]:any}} jsData 
 * @param {string} jsFileName 
 */
function buildAndWriteJs(jsData, jsFileName) {
    const writePath = resolve(__dirname, 'src', '../asset/i18n', jsFileName)
    fs.writeFileSync(writePath, `module.exports=${JSON.stringify(jsData)}`)
}


/**
 * 找到en文件中仍然是中文项
 * @param {*} enFile 
 * @param {*} outXlsFileName 
 */
function findEnStillZh(enFile, outXlsFileName) {
    let xlsData = [['系统位置', '词条(中文)', '词条(英文)', '词条法文', '翻译问题', '解释']];
    const enData = readDataFromJS(enFile);
    foreachJson((key, result) => {
        if (`${result}`.search(/[\u4e00-\u9fa5]/) != -1) {
            xlsData.push([
                key,
                result,
                '',
                '',
                '',
                '',
            ])
        }
    }, enData)
    buildAndWriteXls(xlsData, outXlsFileName ?? '待翻译内容')
}

function replaceJsDataByXlsData(jsFile, xlsFile, keyIndex = 0, useIndex = 2) {
    const [{ data: xlsData }] = readDataFromXLS(xlsFile);
    const jsData = readDataFromJS(jsFile);
    xlsData.splice(1);
    xlsData.forEach(item => {
        let keyArr = item[keyIndex].split('.');
        let tranlateOut = item[useIndex]

        keyArr.forEach((key) => {
            let current = jsData;

            if (typeof current[key] === 'object' && current[key] != null) {
                current = current[key]
            } else {
                current[key] = tranlateOut;
            }
        })
    })
}

/**
 * 将xls文件写成js文件
 * @param {string} xlsFile 
 * @param {string} jsFile 
 * @param { (store:{[key:string]:any},item:Array<any>,index:number)=>void} cb 
 * @param {number} [sheetIndex] 
 */
function writeXlsToJsFile(xlsFile, jsFile, cb, sheetIndex = 0) {
    const xlsData = readDataFromXLS(xlsFile)
    const { data } = xlsData[sheetIndex];

    let result = {};
    foreachXlsData(data, (item, index) => {
        cb(result, item, index)
    })

    buildAndWriteJs(result, jsFile)
}

// writeXlsToJsFile('310translated', '测试.js', (store, item, index) => {
//     const [locationKey, replaceValue] = item;
//     const keyArr = `${locationKey}`.split(".");
//     let current = store;
//     keyArr.forEach((key, index) => {
//         if (index < keyArr.length - 1) {
//             current = current[key] = current[key] ?? {}
//         } else {
//             current[key] = replaceValue
//         }
//     })
// })



// writeJSFileData2Xls(
//     329,
//     '310translated',
//     (store, key, data) => {
//         if (!store.length) store.push([
//             '系统位置',
//             '词条(中文)',
//             '词条(英文)',
//             '词条法文',
//             '翻译问题',
//             '备注',
//         ])
//         store.push([
//             key,
//             data,
//             '',
//             '',
//             '',
//             '',
//         ])
//     })